package hhm.javamode.proxy.dynamic;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

import org.junit.Test;

import hhm.javamode.base.adduser.IUserService;
import hhm.javamode.base.adduser.UserServiceImpl;

public class Client {

	@Test
	public void test1() {
		IUserService userService = new UserServiceImpl();
		// 首先是把userService交给Time做代理，可以输出时间
		TimeHandler timeHandler = new TimeHandler(userService);
		IUserService t1 = (IUserService) Proxy.newProxyInstance(userService.getClass().getClassLoader(),
				userService.getClass().getInterfaces(), timeHandler);

		LogHandler logHandler = new LogHandler(t1);
		IUserService t2 = (IUserService) Proxy.newProxyInstance(userService.getClass().getClassLoader(),
				userService.getClass().getInterfaces(), logHandler);

		t2.addUser("1", "hhm");

	}

	@Test
	public void test2() {
		IUserService userService = new UserServiceImpl();
		// 首先是把userService交给Time做代理，可以输出时间
		TimeHandler timeHandler = new TimeHandler(userService);
		LogHandler logHandler = new LogHandler(getProxy(userService, timeHandler));
		SendHandler sendHandler = new SendHandler(getProxy(userService, logHandler));
		
		IUserService T = getProxy(userService, sendHandler);
		T.addUser("1", "hhm");

	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static <T> T getProxy(final T obj, InvocationHandler handler) {

		ClassLoader loader = obj.getClass().getClassLoader();
		Class[] interfaces = obj.getClass().getInterfaces();
		T t = obj;

		t = (T) Proxy.newProxyInstance(loader, interfaces, handler);

		return t;
	}

}
